package com.powerbank.user.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.powerbank.common.entity.CouponTemplate;
import com.powerbank.common.entity.User;
import com.powerbank.common.entity.UserCoupon;
import com.powerbank.common.exception.BusinessException;
import com.powerbank.common.result.ResultCode;
import com.powerbank.user.mapper.CouponTemplateMapper;
import com.powerbank.user.mapper.UserCouponMapper;
import com.powerbank.user.mapper.UserMapper;
import com.powerbank.user.service.CouponService;
import com.powerbank.user.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 优惠券服务实现类
 */
@Slf4j
@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    private UserCouponMapper userCouponMapper;

    @Autowired
    private CouponTemplateMapper couponTemplateMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<UserCouponVO> getAvailableCoupons(Long userId, String applyScope, BigDecimal amount) {
        log.info("获取用户{}可用优惠券 - 适用范围: {}, 金额: {}", userId, applyScope, amount);

        LambdaQueryWrapper<UserCoupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCoupon::getUserId, userId)
                .eq(UserCoupon::getCouponStatus, 0) // 未使用
                .le(UserCoupon::getValidStartTime, LocalDateTime.now())
                .ge(UserCoupon::getValidEndTime, LocalDateTime.now())
                .and(w -> w.eq(UserCoupon::getApplyScope, "ALL").or().eq(UserCoupon::getApplyScope, applyScope))
                .le(UserCoupon::getMinAmount, amount)
                .orderByAsc(UserCoupon::getValidEndTime); // 按过期时间排序

        List<UserCoupon> coupons = userCouponMapper.selectList(wrapper);
        
        return coupons.stream()
                .map(this::convertToUserCouponVO)
                .collect(Collectors.toList());
    }

    @Override
    public PageResult<UserCouponVO> getUserCoupons(Long userId, Integer status, int page, int size) {
        log.info("查询用户{}优惠券 - 状态: {}, 页码: {}, 页大小: {}", userId, status, page, size);

        Page<UserCoupon> pageParam = new Page<>(page, size);
        LambdaQueryWrapper<UserCoupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCoupon::getUserId, userId);
        
        if (status != null) {
            wrapper.eq(UserCoupon::getCouponStatus, status);
        }
        
        wrapper.orderByDesc(UserCoupon::getCreatedTime);

        Page<UserCoupon> result = userCouponMapper.selectPage(pageParam, wrapper);

        List<UserCouponVO> records = result.getRecords().stream()
                .map(this::convertToUserCouponVO)
                .collect(Collectors.toList());

        return new PageResult<>(records, result.getTotal(), (int) result.getCurrent(), (int) result.getSize());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean receiveCoupon(Long userId, Long templateId) {
        log.info("用户{}领取优惠券模板{}", userId, templateId);

        // 1. 获取优惠券模板
        CouponTemplate template = couponTemplateMapper.selectById(templateId);
        if (template == null || template.getTemplateStatus() != 1) {
            throw new BusinessException(ResultCode.COUPON_NOT_EXIST);
        }

        // 2. 检查是否还有库存
        if (template.getIssuedCount() >= template.getTotalCount()) {
            throw new BusinessException(ResultCode.COUPON_LIMIT_EXCEEDED.getCode(), "优惠券已领完");
        }

        // 3. 检查用户领取限制
        LambdaQueryWrapper<UserCoupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCoupon::getUserId, userId)
                .eq(UserCoupon::getTemplateId, templateId);
        long userReceivedCount = userCouponMapper.selectCount(wrapper);
        
        if (userReceivedCount >= template.getLimitPerUser()) {
            throw new BusinessException(ResultCode.COUPON_LIMIT_EXCEEDED.getCode(), "超过个人领取限制");
        }

        // 4. 计算有效期
        LocalDateTime validStartTime;
        LocalDateTime validEndTime;
        
        if ("FIXED".equals(template.getValidityType())) {
            validStartTime = template.getValidStartTime();
            validEndTime = template.getValidEndTime();
        } else {
            validStartTime = LocalDateTime.now();
            validEndTime = validStartTime.plusDays(template.getValidDays());
        }

        // 5. 创建用户优惠券
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setTemplateId(templateId);
        userCoupon.setCouponCode(generateCouponCode());
        userCoupon.setCouponName(template.getCouponName());
        userCoupon.setCouponType(template.getCouponType());
        userCoupon.setCouponAmount(template.getCouponAmount());
        userCoupon.setDiscountRate(template.getDiscountRate());
        userCoupon.setMinAmount(template.getMinAmount());
        userCoupon.setMaxDiscount(template.getMaxDiscount());
        userCoupon.setApplyScope(template.getApplyScope());
        userCoupon.setCouponStatus(0); // 未使用
        userCoupon.setReceiveTime(LocalDateTime.now());
        userCoupon.setValidStartTime(validStartTime);
        userCoupon.setValidEndTime(validEndTime);
        userCoupon.setReceiveMethod("MANUAL");
        userCoupon.setSourceDesc("用户主动领取");
        userCoupon.setCreatedTime(LocalDateTime.now());
        userCoupon.setUpdatedTime(LocalDateTime.now());

        userCouponMapper.insert(userCoupon);

        // 6. 更新模板统计
        template.setIssuedCount(template.getIssuedCount() + 1);
        template.setUpdatedTime(LocalDateTime.now());
        couponTemplateMapper.updateById(template);

        log.info("用户{}成功领取优惠券 - 优惠券编码: {}", userId, userCoupon.getCouponCode());
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BigDecimal useCoupon(Long userId, Long couponId, Long orderId, String orderNo, BigDecimal amount) {
        log.info("用户{}使用优惠券{} - 订单: {}, 金额: {}", userId, couponId, orderId, amount);

        // 1. 验证优惠券
        if (!validateCoupon(userId, couponId, amount)) {
            throw new BusinessException(ResultCode.COUPON_NOT_AVAILABLE);
        }

        // 2. 获取优惠券
        UserCoupon userCoupon = userCouponMapper.selectById(couponId);

        // 3. 计算优惠金额
        BigDecimal discountAmount = calculateDiscountAmount(couponId, amount);

        // 4. 更新优惠券状态
        userCoupon.setCouponStatus(1); // 已使用
        userCoupon.setUseTime(LocalDateTime.now());
        userCoupon.setOrderId(orderId);
        userCoupon.setOrderNo(orderNo);
        userCoupon.setUpdatedTime(LocalDateTime.now());
        userCouponMapper.updateById(userCoupon);

        // 5. 更新模板统计
        CouponTemplate template = couponTemplateMapper.selectById(userCoupon.getTemplateId());
        if (template != null) {
            template.setUsedCount(template.getUsedCount() + 1);
            template.setUpdatedTime(LocalDateTime.now());
            couponTemplateMapper.updateById(template);
        }

        log.info("优惠券使用成功 - 优惠金额: {}", discountAmount);
        return discountAmount;
    }

    @Override
    public BigDecimal calculateDiscountAmount(Long couponId, BigDecimal amount) {
        UserCoupon userCoupon = userCouponMapper.selectById(couponId);
        if (userCoupon == null) {
            return BigDecimal.ZERO;
        }

        // 检查使用门槛
        if (amount.compareTo(userCoupon.getMinAmount()) < 0) {
            return BigDecimal.ZERO;
        }

        BigDecimal discountAmount = BigDecimal.ZERO;

        switch (userCoupon.getCouponType()) {
            case "DISCOUNT": // 满减券
                discountAmount = userCoupon.getCouponAmount();
                break;
                
            case "RATE": // 折扣券
                discountAmount = amount.multiply(BigDecimal.ONE.subtract(userCoupon.getDiscountRate()));
                // 检查最大优惠金额限制
                if (userCoupon.getMaxDiscount() != null && 
                    discountAmount.compareTo(userCoupon.getMaxDiscount()) > 0) {
                    discountAmount = userCoupon.getMaxDiscount();
                }
                break;
                
            case "CASH": // 代金券
                discountAmount = userCoupon.getCouponAmount();
                // 代金券不能超过订单金额
                if (discountAmount.compareTo(amount) > 0) {
                    discountAmount = amount;
                }
                break;
        }

        return discountAmount;
    }

    @Override
    public boolean validateCoupon(Long userId, Long couponId, BigDecimal amount) {
        UserCoupon userCoupon = userCouponMapper.selectById(couponId);
        
        if (userCoupon == null) {
            return false;
        }

        // 检查所有者
        if (!userCoupon.getUserId().equals(userId)) {
            return false;
        }

        // 检查状态
        if (userCoupon.getCouponStatus() != 0) {
            return false;
        }

        // 检查有效期
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(userCoupon.getValidStartTime()) || now.isAfter(userCoupon.getValidEndTime())) {
            return false;
        }

        // 检查使用门槛
        if (amount.compareTo(userCoupon.getMinAmount()) < 0) {
            return false;
        }

        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean refundCoupon(Long orderId) {
        log.info("退还订单{}使用的优惠券", orderId);

        LambdaQueryWrapper<UserCoupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCoupon::getOrderId, orderId)
                .eq(UserCoupon::getCouponStatus, 1); // 已使用

        List<UserCoupon> usedCoupons = userCouponMapper.selectList(wrapper);

        for (UserCoupon coupon : usedCoupons) {
            // 检查是否还在有效期内
            if (LocalDateTime.now().isBefore(coupon.getValidEndTime())) {
                // 恢复为未使用状态
                coupon.setCouponStatus(0);
                coupon.setUseTime(null);
                coupon.setOrderId(null);
                coupon.setOrderNo(null);
                coupon.setUpdatedTime(LocalDateTime.now());
                userCouponMapper.updateById(coupon);

                // 更新模板统计
                CouponTemplate template = couponTemplateMapper.selectById(coupon.getTemplateId());
                if (template != null) {
                    template.setUsedCount(template.getUsedCount() - 1);
                    template.setUpdatedTime(LocalDateTime.now());
                    couponTemplateMapper.updateById(template);
                }

                log.info("优惠券{}已退还", coupon.getCouponCode());
            } else {
                log.info("优惠券{}已过期，无法退还", coupon.getCouponCode());
            }
        }

        return true;
    }

    @Override
    public List<CouponTemplateVO> getReceivableTemplates(Long userId) {
        log.info("获取用户{}可领取的优惠券模板", userId);

        // 获取启用的模板
        LambdaQueryWrapper<CouponTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CouponTemplate::getTemplateStatus, 1)
                .eq(CouponTemplate::getIssueMethod, "MANUAL")
                .apply("issued_count < total_count");

        List<CouponTemplate> templates = couponTemplateMapper.selectList(wrapper);

        return templates.stream()
                .map(template -> convertToCouponTemplateVO(template, userId))
                .collect(Collectors.toList());
    }

    @Override
    public CouponSummaryVO getCouponSummary(Long userId) {
        log.info("获取用户{}优惠券统计信息", userId);

        CouponSummaryVO summary = new CouponSummaryVO();
        summary.setUserId(userId);

        LambdaQueryWrapper<UserCoupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCoupon::getUserId, userId);

        List<UserCoupon> allCoupons = userCouponMapper.selectList(wrapper);

        int availableCount = 0;
        int usedCount = 0;
        int expiredCount = 0;
        int expiringSoonCount = 0;
        BigDecimal totalSavedAmount = BigDecimal.ZERO;
        BigDecimal monthSavedAmount = BigDecimal.ZERO;

        LocalDateTime now = LocalDateTime.now();
        LocalDateTime monthStart = LocalDate.now().withDayOfMonth(1).atStartOfDay();

        for (UserCoupon coupon : allCoupons) {
            switch (coupon.getCouponStatus()) {
                case 0: // 未使用
                    if (now.isAfter(coupon.getValidEndTime())) {
                        expiredCount++;
                    } else {
                        availableCount++;
                        // 检查是否即将过期（7天内）
                        if (now.plusDays(7).isAfter(coupon.getValidEndTime())) {
                            expiringSoonCount++;
                        }
                    }
                    break;
                case 1: // 已使用
                    usedCount++;
                    // 计算节省金额（这里需要从订单中获取实际优惠金额，简化处理）
                    BigDecimal savedAmount = coupon.getCouponAmount() != null ? 
                            coupon.getCouponAmount() : BigDecimal.ZERO;
                    totalSavedAmount = totalSavedAmount.add(savedAmount);
                    
                    if (coupon.getUseTime() != null && coupon.getUseTime().isAfter(monthStart)) {
                        monthSavedAmount = monthSavedAmount.add(savedAmount);
                    }
                    break;
                case 2: // 已过期
                    expiredCount++;
                    break;
            }
        }

        summary.setAvailableCouponCount(availableCount);
        summary.setUsedCouponCount(usedCount);
        summary.setExpiredCouponCount(expiredCount);
        summary.setExpiringSoonCount(expiringSoonCount);
        summary.setTotalReceivedCount(allCoupons.size());
        summary.setTotalSavedAmount(totalSavedAmount);
        summary.setMonthSavedAmount(monthSavedAmount);

        // 获取可领取优惠券数量
        List<CouponTemplateVO> receivableTemplates = getReceivableTemplates(userId);
        summary.setReceivableCount(receivableTemplates.size());
        summary.setRecommendedCount(Math.min(3, receivableTemplates.size())); // 推荐前3个

        return summary;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int issueNewUserCoupons(Long userId) {
        log.info("为新用户{}发放优惠券", userId);

        // 获取新用户优惠券模板
        LambdaQueryWrapper<CouponTemplate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CouponTemplate::getTemplateStatus, 1)
                .eq(CouponTemplate::getIssueMethod, "AUTO")
                .like(CouponTemplate::getDescription, "新用户");

        List<CouponTemplate> newUserTemplates = couponTemplateMapper.selectList(wrapper);
        int issuedCount = 0;

        for (CouponTemplate template : newUserTemplates) {
            try {
                if (template.getIssuedCount() < template.getTotalCount()) {
                    issueUserCoupon(userId, template, "AUTO", "新用户注册礼包");
                    issuedCount++;
                }
            } catch (Exception e) {
                log.error("发放新用户优惠券失败", e);
            }
        }

        log.info("为新用户{}发放了{}张优惠券", userId, issuedCount);
        return issuedCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int issueBirthdayCoupons(Long userId) {
        log.info("为用户{}发放生日优惠券", userId);

        User user = userMapper.selectById(userId);
        if (user == null || user.getBirthday() == null) {
            return 0;
        }

        LocalDate today = LocalDate.now();
        LocalDate birthday = user.getBirthday();

        // 检查是否是生日
        if (today.getMonth() != birthday.getMonth() || today.getDayOfMonth() != birthday.getDayOfMonth()) {
            return 0;
        }

        // 检查今年是否已发放
        LambdaQueryWrapper<UserCoupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCoupon::getUserId, userId)
                .eq(UserCoupon::getReceiveMethod, "AUTO")
                .like(UserCoupon::getSourceDesc, "生日")
                .ge(UserCoupon::getReceiveTime, today.atStartOfDay())
                .lt(UserCoupon::getReceiveTime, today.plusDays(1).atStartOfDay());

        if (userCouponMapper.selectCount(wrapper) > 0) {
            log.info("用户{}今年已领取过生日优惠券", userId);
            return 0;
        }

        // 获取生日优惠券模板
        LambdaQueryWrapper<CouponTemplate> templateWrapper = new LambdaQueryWrapper<>();
        templateWrapper.eq(CouponTemplate::getTemplateStatus, 1)
                .eq(CouponTemplate::getIssueMethod, "AUTO")
                .like(CouponTemplate::getDescription, "生日");

        List<CouponTemplate> birthdayTemplates = couponTemplateMapper.selectList(templateWrapper);
        int issuedCount = 0;

        for (CouponTemplate template : birthdayTemplates) {
            try {
                if (template.getIssuedCount() < template.getTotalCount()) {
                    issueUserCoupon(userId, template, "AUTO", "生日专属礼品");
                    issuedCount++;
                }
            } catch (Exception e) {
                log.error("发放生日优惠券失败", e);
            }
        }

        log.info("为用户{}发放了{}张生日优惠券", userId, issuedCount);
        return issuedCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean exchangeCoupon(Long userId, String couponCode) {
        log.info("用户{}兑换优惠券 - 兑换码: {}", userId, couponCode);

        // 1. 根据兑换码查找优惠券模板
        LambdaQueryWrapper<CouponTemplate> templateWrapper = new LambdaQueryWrapper<>();
        templateWrapper.eq(CouponTemplate::getTemplateCode, couponCode)
                .eq(CouponTemplate::getTemplateStatus, 1);

        CouponTemplate template = couponTemplateMapper.selectOne(templateWrapper);
        if (template == null) {
            throw new BusinessException(ResultCode.COUPON_NOT_EXIST.getCode(), "兑换码无效");
        }

        // 2. 检查是否还有库存
        if (template.getIssuedCount() >= template.getTotalCount()) {
            throw new BusinessException(ResultCode.COUPON_LIMIT_EXCEEDED.getCode(), "优惠券已兑换完");
        }

        // 3. 检查用户是否已兑换过
        LambdaQueryWrapper<UserCoupon> userCouponWrapper = new LambdaQueryWrapper<>();
        userCouponWrapper.eq(UserCoupon::getUserId, userId)
                .eq(UserCoupon::getTemplateId, template.getId());

        if (userCouponMapper.selectCount(userCouponWrapper) > 0) {
            throw new BusinessException(ResultCode.COUPON_LIMIT_EXCEEDED.getCode(), "您已兑换过此优惠券");
        }

        // 4. 发放优惠券
        issueUserCoupon(userId, template, "EXCHANGE", "兑换码兑换");

        log.info("用户{}兑换优惠券成功", userId);
        return true;
    }

    /**
     * 发放用户优惠券
     */
    private void issueUserCoupon(Long userId, CouponTemplate template, String receiveMethod, String sourceDesc) {
        // 计算有效期
        LocalDateTime validStartTime;
        LocalDateTime validEndTime;
        
        if ("FIXED".equals(template.getValidityType())) {
            validStartTime = template.getValidStartTime();
            validEndTime = template.getValidEndTime();
        } else {
            validStartTime = LocalDateTime.now();
            validEndTime = validStartTime.plusDays(template.getValidDays());
        }

        // 创建用户优惠券
        UserCoupon userCoupon = new UserCoupon();
        userCoupon.setUserId(userId);
        userCoupon.setTemplateId(template.getId());
        userCoupon.setCouponCode(generateCouponCode());
        userCoupon.setCouponName(template.getCouponName());
        userCoupon.setCouponType(template.getCouponType());
        userCoupon.setCouponAmount(template.getCouponAmount());
        userCoupon.setDiscountRate(template.getDiscountRate());
        userCoupon.setMinAmount(template.getMinAmount());
        userCoupon.setMaxDiscount(template.getMaxDiscount());
        userCoupon.setApplyScope(template.getApplyScope());
        userCoupon.setCouponStatus(0); // 未使用
        userCoupon.setReceiveTime(LocalDateTime.now());
        userCoupon.setValidStartTime(validStartTime);
        userCoupon.setValidEndTime(validEndTime);
        userCoupon.setReceiveMethod(receiveMethod);
        userCoupon.setSourceDesc(sourceDesc);
        userCoupon.setCreatedTime(LocalDateTime.now());
        userCoupon.setUpdatedTime(LocalDateTime.now());

        userCouponMapper.insert(userCoupon);

        // 更新模板统计
        template.setIssuedCount(template.getIssuedCount() + 1);
        template.setUpdatedTime(LocalDateTime.now());
        couponTemplateMapper.updateById(template);
    }

    /**
     * 生成优惠券码
     */
    private String generateCouponCode() {
        return "CPN" + System.currentTimeMillis() + RandomUtil.randomLong(1000, 9999);
    }

    /**
     * 转换为用户优惠券VO
     */
    private UserCouponVO convertToUserCouponVO(UserCoupon userCoupon) {
        UserCouponVO vo = new UserCouponVO();
        BeanUtils.copyProperties(userCoupon, vo);
        
        vo.setCouponTypeDesc(getCouponTypeDesc(userCoupon.getCouponType()));
        vo.setApplyScopeDesc(getApplyScopeDesc(userCoupon.getApplyScope()));
        vo.setCouponStatusDesc(getCouponStatusDesc(userCoupon.getCouponStatus()));
        
        // 计算剩余天数
        LocalDateTime now = LocalDateTime.now();
        if (userCoupon.getCouponStatus() == 0 && now.isBefore(userCoupon.getValidEndTime())) {
            long remainingDays = ChronoUnit.DAYS.between(now, userCoupon.getValidEndTime());
            vo.setRemainingDays((int) remainingDays);
            vo.setExpiringSoon(remainingDays <= 7);
        }
        
        // 设置使用条件和优惠描述
        vo.setUsageCondition(buildUsageCondition(userCoupon));
        vo.setDiscountDesc(buildDiscountDesc(userCoupon));
        
        return vo;
    }

    /**
     * 转换为优惠券模板VO
     */
    private CouponTemplateVO convertToCouponTemplateVO(CouponTemplate template, Long userId) {
        CouponTemplateVO vo = new CouponTemplateVO();
        BeanUtils.copyProperties(template, vo);
        
        vo.setCouponTypeDesc(getCouponTypeDesc(template.getCouponType()));
        vo.setApplyScopeDesc(getApplyScopeDesc(template.getApplyScope()));
        vo.setRemainingCount(template.getTotalCount() - template.getIssuedCount());
        
        // 查询用户已领取数量
        LambdaQueryWrapper<UserCoupon> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserCoupon::getUserId, userId)
                .eq(UserCoupon::getTemplateId, template.getId());
        int userReceivedCount = userCouponMapper.selectCount(wrapper).intValue();
        vo.setUserReceivedCount(userReceivedCount);
        
        // 判断是否可领取
        boolean canReceive = true;
        String cannotReceiveReason = null;
        
        if (template.getIssuedCount() >= template.getTotalCount()) {
            canReceive = false;
            cannotReceiveReason = "优惠券已领完";
        } else if (userReceivedCount >= template.getLimitPerUser()) {
            canReceive = false;
            cannotReceiveReason = "超过个人领取限制";
        }
        
        vo.setCanReceive(canReceive);
        vo.setCannotReceiveReason(cannotReceiveReason);
        
        // 设置描述
        vo.setUsageCondition(buildUsageCondition(template));
        vo.setDiscountDesc(buildDiscountDesc(template));
        
        return vo;
    }

    /**
     * 获取优惠券类型描述
     */
    private String getCouponTypeDesc(String couponType) {
        switch (couponType) {
            case "DISCOUNT":
                return "满减券";
            case "RATE":
                return "折扣券";
            case "CASH":
                return "代金券";
            default:
                return "未知";
        }
    }

    /**
     * 获取适用范围描述
     */
    private String getApplyScopeDesc(String applyScope) {
        switch (applyScope) {
            case "ALL":
                return "全场通用";
            case "DEPOSIT":
                return "押金专用";
            case "FEE":
                return "费用专用";
            default:
                return "未知";
        }
    }

    /**
     * 获取优惠券状态描述
     */
    private String getCouponStatusDesc(Integer couponStatus) {
        switch (couponStatus) {
            case 0:
                return "未使用";
            case 1:
                return "已使用";
            case 2:
                return "已过期";
            case 3:
                return "已冻结";
            default:
                return "未知";
        }
    }

    /**
     * 构建使用条件描述
     */
    private String buildUsageCondition(UserCoupon coupon) {
        if (coupon.getMinAmount().compareTo(BigDecimal.ZERO) > 0) {
            return "满" + coupon.getMinAmount() + "元可用";
        }
        return "无门槛使用";
    }

    private String buildUsageCondition(CouponTemplate template) {
        if (template.getMinAmount().compareTo(BigDecimal.ZERO) > 0) {
            return "满" + template.getMinAmount() + "元可用";
        }
        return "无门槛使用";
    }

    /**
     * 构建优惠描述
     */
    private String buildDiscountDesc(UserCoupon coupon) {
        switch (coupon.getCouponType()) {
            case "DISCOUNT":
                return "立减" + coupon.getCouponAmount() + "元";
            case "RATE":
                String rate = coupon.getDiscountRate().multiply(new BigDecimal("10")).toString();
                String desc = rate + "折";
                if (coupon.getMaxDiscount() != null) {
                    desc += "（最高减" + coupon.getMaxDiscount() + "元）";
                }
                return desc;
            case "CASH":
                return "抵扣" + coupon.getCouponAmount() + "元";
            default:
                return "";
        }
    }

    private String buildDiscountDesc(CouponTemplate template) {
        switch (template.getCouponType()) {
            case "DISCOUNT":
                return "立减" + template.getCouponAmount() + "元";
            case "RATE":
                String rate = template.getDiscountRate().multiply(new BigDecimal("10")).toString();
                String desc = rate + "折";
                if (template.getMaxDiscount() != null) {
                    desc += "（最高减" + template.getMaxDiscount() + "元）";
                }
                return desc;
            case "CASH":
                return "抵扣" + template.getCouponAmount() + "元";
            default:
                return "";
        }
    }
}